package com.ojoin.trade.common.web.notifications;

import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.domain.Notification;
import com.ojoin.trade.common.web.domain.NotificationTemplate;
import com.ojoin.trade.common.web.domain.NotificationType;
import com.ojoin.trade.common.web.service.impl.NotificationService;
import com.ojoin.trade.common.web.service.impl.NotificationTemplateService;

public class NotificationAPIServiceImpl  implements NotificationAPIService {
    private static final Logger LOG = LoggerFactory.getLogger(NotificationAPIServiceImpl.class);

    @Autowired
    private NotificationTemplateService notificationTemplateService;

    @Autowired
    private NotificationService notificationDataService;
    
    
     
    @Override
    public boolean isFirst(NotificationType type) {
    	Notification nd=new Notification();
    	nd.setType(type);
    	Long count=notificationDataService.queryCount(nd);
        return (count == null||count.intValue()==0);
    }


    @Override
    public boolean publishIfFirst(Notification notification) {
        if (notification.getDate() == null) {
            notification.setDate(TimeUtils.nowUTC());
        }

        if (!isFirst(notification.getType())) {
            return false;
        }
        
        notificationDataService.insert(notification);

        return true;
    }

    

    @Override
    public int fixedAllByType(NotificationType type) {
        return notificationDataService.fixed(type.name());
    }


    public void notify(final Integer userId, final String templateName, final Map<String, Object> context) {
        NotificationTemplate template = notificationTemplateService.findByName(templateName);

        if(template == null) {
            throw new BusinessException("模板没找到->"+templateName);
        }

        Notification data = new Notification();

        data.setUserId(userId);
        data.setType(template.getType());
        data.setDate(new Date());

        String content = template.getTemplate();
        String title = template.getTitle();
        if(context != null) {
            for(String key : context.keySet()) {
                title = title.replace("{{" + key + "}}", String.valueOf(context.get(key)));
                content = content.replace("{{" + key + "}}", String.valueOf(context.get(key)));
            }
        }

        data.setTitle(title);
        data.setContent(content);

        notificationDataService.insert(data);
    }

}
